import requests
# from fake_useragent import UserAgent
import json
import random
import time
import redis
# if 'zhijie' in 'zhijie12':
#     print('czh')
# m_id = 5
# sql_2 = "SELECT rank,current_rank,status FROM tb_work WHERE id={} and ls_delete=0 and status=1".format(m_id)
# print(sql_2)

def checkout_time(mdb,a=0): #随机提取一个ip有效时长大于300秒的IP
    shu = a
    ip_port = ''
    api_url2 = "https://dps.kdlapi.com/api/getdps/?orderid=900326243484182&signature=adkpykyxm3kzi8hm2tg9p2gaq8sud1p2&num=1&pt=1&format=json&sep=1"
    proxy_ip_s = requests.get(api_url2).text
    proxy_list = json.loads(proxy_ip_s)['data']['proxy_list']
    li_time = []
    ip_boolean_list = []
    ip_boolean_api = 'https://dps.kdlapi.com/api/checkdpsvalid'
    params = {
        'orderid': '900326243484182',
        'proxy': ','.join(proxy_list),
        'signature': 'adkpykyxm3kzi8hm2tg9p2gaq8sud1p2',
    }

    ip_true = requests.get(ip_boolean_api, params=params).text #校验IP有效性
    ip_true = json.loads(ip_true)
    for ip,valid in ip_true['data'].items():
        if valid:
            ip_boolean_list.append(ip)

    api_timeout = 'https://dps.kdlapi.com/api/getdpsvalidtime'
    params['proxy'] = ','.join(ip_boolean_list)
    proxy_timeout = requests.get(api_timeout,params=params).text #校验IP时长
    proxy_timeout = json.loads(proxy_timeout)
    data_ip = proxy_timeout['data'].items()
    if data_ip:
        for key,value in data_ip:
            if int(value)>300:
                li_time.append(key)
    # ip_port = random.choice(li_time)
    for i in li_time:
        val = mdb.hexists('ip_port', i)
        if not val:
            mdb.hset('ip_port', i, i)
            ip_port = i
            return ip_port
    if not ip_port:
        time.sleep(3)
        if shu<=10:
            shu += 1
            # print('ip存在，递归进入')
            ip_port = checkout_time(mdb,shu)
        else:
            # print('没办法！只能选这个了')
            if li_time:
                ip_port = random.choice(li_time)
            else:
                ip_port = '103.85.85.247:22'
        return ip_port



if __name__=='__main__':
    mdb = redis.StrictRedis(host='127.0.0.1', port=6379, db=0, decode_responses=True, password='ma1114')  #
    ip_port = checkout_time(mdb)
    print(ip_port)
    # pass
